package com.lipert.sk2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;



public class Sender {

	public byte[] buffer = "alaakak".getBytes();
	public DatagramPacket packet;
	public DatagramSocket socket;
	InetAddress friend;
	int port;// = 9999;

	public void sendPrivate(byte[] data) {
		buffer = data;
		packet = new DatagramPacket(buffer, buffer.length, friend, port);
		try {
			socket = new DatagramSocket();
		} catch (SocketException e1) {
			
			e1.printStackTrace();
		}
		System.out.println("wysylam");
		System.out.println("XXX: " + new String(packet.getData()).trim());
		try {
			socket.send(packet);
		} catch (IOException e) {
			
			e.printStackTrace();
		}

		socket.close();
	}

	public void sendPublic(byte[] data) {
		buffer = data;
		packet = new DatagramPacket(buffer, buffer.length, friend, port);

		try {
			socket = new DatagramSocket();
		} catch (SocketException e1) {
			
			e1.printStackTrace();
		}
		System.out.println("XXX: " + new String(packet.getData()).trim());
		try {
			socket.send(packet);
		} catch (IOException e) {
			
			e.printStackTrace();
		}

		socket.close();
	}

	public void sendToServer(String message) {
		//Socket serverSocket = null;
		//PrintWriter out = null;
		//BufferedReader in = null;

		try {
			//ServerReceiver.serverSocket = new Socket(InetAddress.getByName("127.0.0.1"), 8888);
			
			//System.out.println(ServerReceiver.serverSocket.getPort());
			ServerReceiver.out = new PrintWriter(ServerReceiver.serverSocket.getOutputStream(), true);
			//in = new BufferedReader(new InputStreamReader(
            //        ServerReceiver.serverSocket.getInputStream()));
		} catch (UnknownHostException e) {
			
			e.printStackTrace();
		} catch (IOException e) {
			
			e.printStackTrace();
		}
		;
		
		String userInput = null;
		userInput = message;
		OutputStream outStream = null;
		try {
			outStream = ServerReceiver.serverSocket.getOutputStream();
		} catch (IOException e) {
			
			e.printStackTrace();
		} 
		
		// PrintWriter out = new PrintWriter(outStream, true /*autoFlush*/);

		
			
				ServerReceiver.out.println(userInput);
				//System.out.println("echo: " + in.readLine());
			
		
		
	//	ServerReceiver.out.close();
		
			//in.close();
			
			//serverSocket.close();
		
		
	}
/*
 * 
 * 
 
 * */
	public void connection(String address, int port) {

		try {

			this.port = port;
			friend = InetAddress.getByName(address);
			// packet = new DatagramPacket(buffer, buffer.length, this.friend,
			// port);
		} catch (UnknownHostException e) {
			
			e.printStackTrace();
		}
	}

}
